package com.newpage.module_lecture.activity;

import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Timeline;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.newpage.module_lecture.R;
import com.newpage.module_lecture.adapter.ExplainTeacherAdapter;
import com.newpage.module_lecture.adapter.QuestionExplainAdapter;
import com.newpage.module_lecture.contract.LectureContract;
import com.newpage.module_lecture.presenter.LecturePresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wetao.lib_common.ConstantArouter;
import com.wetao.lib_common.Constants;
import com.wetao.lib_common.base.BaseActivity;
import com.wetao.lib_common.base.BaseResponse;
import com.wetao.lib_common.bean.response.ExplainBean;
import com.wetao.lib_common.bean.response.QuestionExplainListInfo;
import com.wetao.lib_common.tsdBlePen.TsdService;
import com.wetao.lib_common.utils.ComUtil;
import com.wetao.lib_common.utils.JsonUtils;
import com.wetao.lib_common.utils.LogUtils;
import com.wetao.lib_common.utils.ToastUtil;
import com.wetao.lib_common.video.AudioPlayerManager;
import com.wetao.lib_common.view.CustomPopWindow;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 讲题微课页面
 */

@Route(path = ConstantArouter.PATH_LECTURE_LECTUREMAINACTIVITY)
public class LectureMainActivity extends BaseActivity<LectureContract.View, LecturePresenter> implements LectureContract.View,AudioPlayerManager.CallbackPlay {

    private RecyclerView rv_lecture;
    private QuestionExplainAdapter explainAdapter;
    private List<QuestionExplainListInfo.Data.RecordsBean> mData = new ArrayList<>();

    private SmartRefreshLayout srl;
    private RelativeLayout rl_lecture_noData;


    //老师选项
    private RecyclerView rcy_pop_teacher;
    private ExplainTeacherAdapter explainTeacherAdapter;
    //老师讲解集合
    private List<ExplainBean> explainListBeans = new ArrayList<>();
    private CustomPopWindow popWindowTeacher;


    private String audioPath;
    private boolean startTimer = false; //是否开始播放批注
    private long mDuration;
    private int curAudioIndex = -1;
    private int curParentIndex = -1; //item讲解弹框索引
    private AudioManager audioManager;

    //最大音量
    int maxVolume;
    //当前音量
    int currentVolume;

    int current = 1;
    int pages = 1;
    int total = 1;
    int PAGESIZE = 10;
    int PAGE = 1;



    @Override
    public int getLayoutId() {
        return R.layout.lecture_activity_main;
    }

    @Override
    public LecturePresenter createPresenter() {
        return new LecturePresenter(this);
    }

    @Override
    public LectureContract.View createView() {
        return this;
    }

    @Override
    public void init() {
        initTitleLayout();
        setTvTitle("讲题微课", true);
        initVolume();
        initAudioPlay();
        initView();
        initEvent();
        initRecycleView();
        getQuestionExplainReq(current,PAGESIZE);
    }




    private void initAudioPlay () {

        AudioPlayerManager.getInstance(this).setCallbackPlay(this);
        AudioPlayerManager.getInstance(this).playWithCompletionListener(audioPath, new Player.EventListener() {
            @Override
            public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
                LogUtils.i("onTimelineChanged start");
            }

            @Override
            public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
                LogUtils.i("onTracksChanged start");
            }

            @Override
            public void onLoadingChanged(boolean isLoading) {
                LogUtils.i("onLoadingChanged start");
            }

            @Override
            public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                LogUtils.i("onPlayerStateChanged start platbackState is " + playbackState + "===" + playWhenReady);
                if (AudioPlayerManager.getInstance(LectureMainActivity.this).isPlaying() && !startTimer) {
                    startTimer = true;
                    AudioPlayerManager.getInstance(LectureMainActivity.this).updateSeekBar();
                    mDuration = AudioPlayerManager.getInstance(LectureMainActivity.this).getMediaPlayer().getDuration();

                }
                if (playbackState == Player.STATE_ENDED) {
                    startTimer = false;
                    AudioPlayerManager.getInstance(LectureMainActivity.this).reset(0);
                    AudioPlayerManager.getInstance(LectureMainActivity.this).refreshPosition(true);
                    explainAdapter.musicCompletion();
                }

//                if (playbackState == Player.STATE_IDLE || playbackState == Player.STATE_ENDED) {
//                    playWhenReady = false;
//                }
//                setPlayView(playWhenReady);
            }

            @Override
            public void onRepeatModeChanged(int repeatMode) {
                LogUtils.i("onRepeatModeChanged start");
            }

            @Override
            public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
                LogUtils.i("onShuffleModeEnabledChanged start");
            }

            @Override
            public void onPlayerError(ExoPlaybackException error) {
                LogUtils.i("onPlayerError start");
            }

            @Override
            public void onPositionDiscontinuity(int reason) {
                LogUtils.i("onPositionDiscontinuity start");
            }

            @Override
            public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
                LogUtils.i("onPlaybackParametersChanged start");
            }

            @Override
            public void onSeekProcessed() {
                LogUtils.i("onSeekProcessed start");
            }
        });
    }


    private void setPlayView(boolean playWhenReady) {
       explainAdapter.musicPause(playWhenReady);
    }

    /**
     * 播放或暂停
     */
    private void onPlayOrPause () {
        if (startTimer) {
            startTimer = false;
        }
        AudioPlayerManager.getInstance(this).playOrPause();
    }
    

    private void initVolume() {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }


    private void showTeacherPop(View view, QuestionExplainListInfo.Data.RecordsBean bean,
                                int pos, ExplainBean explainBean) {

        View popView = LayoutInflater.from(this).inflate(R.layout.lecture_teacher_pop, null);
        initPopRcyView(popView, bean, pos, explainBean);
        popWindowTeacher = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(popView)
                .setFocusable(true)
                .setOutsideTouchable(true)
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {

                    }
                }).create();

        int[] xy = new int[2];
        view.getLocationOnScreen(xy);
        int offset = popWindowTeacher.getHeight() + view.getHeight();
        if (xy[1] > (ComUtil.getScreenHeight(LectureMainActivity.this) - offset) /*&& pos == mData.size() - 1*/){
            popWindowTeacher.showAsDropDown(view,0,-offset);
        }else {
            popWindowTeacher.showAsDropDown(view,0, 14);
        }
//        LogUtils.e("x ==" + xy[0] + "y==" + xy[1]);

    }

    /**
     *初始化讲解
     * @param rootView
     */
    private void initPopRcyView(View rootView, final QuestionExplainListInfo.Data.RecordsBean bean,
                                int parentPos, ExplainBean explainBean) {

        explainListBeans.clear();
        explainListBeans.addAll(bean.getExplainList());
        rcy_pop_teacher = rootView.findViewById(R.id.rcy_pop_teacher);
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        explainTeacherAdapter = new ExplainTeacherAdapter(explainListBeans, parentPos, explainBean);
        explainTeacherAdapter.setOnItemClickListener(new ExplainTeacherAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                if (AudioPlayerManager.getInstance(LectureMainActivity.this).isPlaying() && curParentIndex == parentPos){
                    onPlayOrPause();
                    setPlayView(false);
                }
                explainAdapter.setExplainTeacher(explainListBeans.get(position), parentPos);
                popWindowTeacher.dissmiss();
            }
        });

        rcy_pop_teacher.setLayoutManager(mLayoutManager);
        rcy_pop_teacher.setAdapter(explainTeacherAdapter);
        rcy_pop_teacher.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }

    /**
     * 请求数据
     */
    private void getQuestionExplainReq(int cur,int pageSize) {
        getPresenter().getQuestionExplainList(ComUtil.getHashmapByStr(new String[]{"pageNo","pageSize"}, new String[]{String.valueOf(cur), String.valueOf(pageSize)}), true, false);
    }

    /**
     * 请求掌握情况
     */
    private void updateUnderStandReq(Integer id, Integer isUnderstand) {
        getPresenter().updateUnderstand((HashMap<String, Object>) ComUtil.getHashmapByStr(new String[]{"id", "isUndrestand"}, new Object[]{id, isUnderstand}), false, false);
    }


    /**
     * 初始化列表
     */
    private void initRecycleView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        rv_lecture.setLayoutManager(linearLayoutManager);
        explainAdapter = new QuestionExplainAdapter(this);
        explainAdapter.updateVolume(currentVolume);
        explainAdapter.setHasStableIds(true);
        explainAdapter.setRecordItemClickListener(new QuestionExplainAdapter.OnItemClickListener() {

            @Override
            public void OnItemClickListener(int position) {

            }

            @Override
            public void onPopClick(View view, QuestionExplainListInfo.Data.RecordsBean bean, int pos, ExplainBean explainBean) {
                showTeacherPop(view, bean, pos, explainBean);
            }

            @Override
            public void onVideoPlayClick(QuestionExplainListInfo.Data.RecordsBean recordsBean, ExplainBean explainBean) {
                if (explainBean.getExplainType()!=null && explainBean.getExplainType() == Constants.TYPE_VIDEO){
                    ARouter.getInstance().build(ConstantArouter.PATH_LECTURE_LECTUREVIDEOACTIVITY)
                            .withString("videoInfo", JsonUtils.toJson(explainBean))
                            .withString("title", recordsBean.getExamName())
                            .navigation();
                } else if (explainBean.getExplainType()!=null && explainBean.getExplainType() == Constants.TYPE_TRACK) {
                    //播放音轨 下标重置
                    ARouter.getInstance().build(ConstantArouter.PATH_LECTURE_LECTUREPLAYVIDEOEXPLAINACTIVITY)
                            .withString("explainName", explainBean.getExplainName())
                            .withString("explainUrl", explainBean.getExplainUrl())
                            .withInt("explainType", explainBean.getExplainType())
                            .withInt("videoTime", explainBean.getVideoTime())
                            .navigation();
                }
            }

            @Override
            public void onAudioPlayClick(String path,int pos) {
                if (curAudioIndex != pos) {
                    curAudioIndex = pos;
                    startTimer = false;
                    LogUtils.e("onAudioPlayClick change =" + path);
                    explainAdapter.resetRangeSeek(pos);
                    AudioPlayerManager.getInstance(LectureMainActivity.this).stop(true);
                    AudioPlayerManager.getInstance(LectureMainActivity.this).changeAudioUrl(path);
                } else {
                    LogUtils.e("onAudioPlayClick not change  =" + pos);
                    onPlayOrPause();
                }
                curParentIndex = pos;
            }

            @Override
            public void onVoiceClick() {
                if (currentVolume > 0) {
                    currentVolume = 0;
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
                } else {
                    currentVolume = maxVolume / 2;
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
                }
                explainAdapter.updateVolume(currentVolume);
                LogUtils.i("volume ==" + currentVolume);
            }


            @Override
            public void onUnderStandEventClick(Integer id, Integer isUnderstand) {
                updateUnderStandReq(id, isUnderstand);
                explainAdapter.notifyDataSetChanged();
            }

            @Override
            public void onRangeSeekBarChange(int cur, int i) {
                LogUtils.e("onRangeSeekBarChange cur postion == " + cur);
                if (i == curAudioIndex){
                    setCurAndTotalView(cur,mDuration);
                    AudioPlayerManager.getInstance(LectureMainActivity.this).getMediaPlayer().seekTo(cur);
                    explainAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onPathError(int i) {
                ToastUtil.initToast("该音频地址格式错误，无法播放");
            }
        });


        rv_lecture.setAdapter(explainAdapter);
    }




    private void initView() {
        rv_lecture = findViewById(R.id.rv_lecture);
        srl = findViewById(R.id.lecture_refresh_layout);
        rl_lecture_noData = findViewById(R.id.rl_lecture_noData);

    }

    private void initEvent() {
        iv_back.setOnClickListener(v -> {
            finish();
        });

        rl_lecture_noData.setOnClickListener(v->{
            getQuestionExplainReq(current,PAGESIZE);
        });

        srl.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onRefresh(@NonNull @NotNull RefreshLayout refreshLayout) {
                getQuestionExplainReq(1,PAGESIZE);
            }

            @Override
            public void onLoadMore(@NonNull @NotNull RefreshLayout refreshLayout) {
                if (current < pages){
                    getQuestionExplainReq(++current,PAGESIZE);
                }else {
                    refreshLayout.finishLoadMoreWithNoMoreData();
                }
            }
        });
        srl.setRefreshHeader(new ClassicsHeader(this));
        srl.setRefreshFooter(new ClassicsFooter(this));
    }


    private void showEmpty() {
        if (explainAdapter.getItemCount() > 0) {
            rl_lecture_noData.setVisibility(View.GONE);
            srl.setVisibility(View.VISIBLE);
        } else {
            rl_lecture_noData.setVisibility(View.VISIBLE);
            srl.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean getIsBindTsdService() {
        return false;
    }

    @Override
    public TsdService.OnDataReceiveListener getTsdServiceDataReceiveListener() {
        return null;
    }


    private void finishRefresh(){
        if (current == 1){
           mData.clear();
        }

        if(srl != null) {
            srl.finishRefresh();
            srl.finishLoadMore();
            srl.resetNoMoreData();//去除没有更多数据状态
        }
    }

    @Override
    public void getQuestionExplainResult(QuestionExplainListInfo resp) {
        finishRefresh();
        if (resp.getData() != null && resp.getData().getRecords().size() > 0) {
            pages = resp.getData().getPages();
            PAGESIZE = resp.getData().getSize();
            total = resp.getData().getTotal();
            mData.addAll(resp.getData().getRecords());
        }
        explainAdapter.setExplainTeacherList(mData);
        showEmpty();
    }

    @Override
    public void getQuestionExplainFail() {
        finishRefresh();
    }

    @Override
    public void updateUnderstandSuccess(BaseResponse resp) {

    }

    @Override
    public void updateUnderstandFail() {

    }


    @Override
    protected void onPause() {
        super.onPause();
        if (AudioPlayerManager.getInstance(this).isPlaying()){
            onPlayOrPause();
            setPlayView(false);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        AudioPlayerManager.getInstance(LectureMainActivity.this).stop(false);
        AudioPlayerManager.getInstance(LectureMainActivity.this).release();
    }

    @Override
    public void onCurrentPosition(Bundle bundle) {
        long cur = bundle.getLong(AudioPlayerManager.STR_CURRENT_POSITION);
        long dur = bundle.getLong(AudioPlayerManager.STR_DURATION);
        LogUtils.e("setCurAndTotalView cur ==" + cur + ",dur==" + dur);
        if (dur < 0 || cur == 0) return;
        setCurAndTotalView(cur,dur);

    }

    private void setCurAndTotalView (long cur,long dur){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                explainAdapter.updateCurrentTime(cur,dur);
                explainAdapter.notifyDataSetChanged();
            }
        });

    }
}